import 'package:chat_app_project/const/sys_const.dart';
import 'package:chat_app_project/dao/im_dao.dart';
import 'package:chat_app_project/tool/audio_player.dart';
import 'package:chat_app_project/tool/time.dart';
import 'package:flutter/material.dart';
import 'package:wukongimfluttersdk/entity/channel.dart';
import 'package:wukongimfluttersdk/entity/conversation.dart';
import 'package:wukongimfluttersdk/type/const.dart';
import 'package:wukongimfluttersdk/wkim.dart';

import '../../constants.dart';
import '../../models/const.dart';
import '../../models/contestation.dart';
import '../../models/res_entity.dart';
import '../../models/user_login_info_entity.dart';
import '../../tool/event_bus.dart';
import '../../util/notification_helper.dart';
import '../../util/sp_util.dart';
import '../messages/message_screen.dart';

class ConversationPage extends StatelessWidget {
  const ConversationPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListViewShowData(),
    );
  }
}

class ListViewShowData extends StatefulWidget {
  const ListViewShowData({super.key});

  @override
  State<StatefulWidget> createState() {
    return ListViewShowDataState();
  }
}

class ListViewShowDataState extends State<ListViewShowData> {
  List<UIConversation> msgList = [];
  UserLoginInfoEntity loginInfoEntity = UserLoginInfoEntity();

  //通知
  NotificationHelper notificationHelper = NotificationHelper();

  @override
  void initState() {
    super.initState();
    //登录初始化
    UserInfo.isLogin(predicate: () {
      //初始化监听
      _initListener();
      //获取会话数据
      _getDataList();
    });

    Map<String, dynamic>? loginInfo = SpUtil.getObject("loginInfo");
    if (loginInfo != null) {
      loginInfoEntity = UserLoginInfoEntity.fromJson(loginInfo);
    }
  }

  var _connectionStatusStr = '未连接';

  _initListener() {
    //连接件状态监听
    WKIM.shared.connectionManager.addOnConnectionStatus('home',
        (status, reason) {
      if (status == WKConnectStatus.connecting) {
        _connectionStatusStr = '连接中...';
      } else if (status == WKConnectStatus.success) {
        _connectionStatusStr = '最近会话';
      } else if (status == WKConnectStatus.noNetwork) {
        _connectionStatusStr = '网络异常';
      } else if (status == WKConnectStatus.syncMsg) {
        _connectionStatusStr = '同步消息中...';
      }
      setState(() {});
    });

    //会话
    WKIM.shared.conversationManager.addOnRefreshMsgListener('chat_conversation',
        (msg, isEnd) async {
      bool isAdd = true;
      UIConversation? uiConversation;
      for (var i = 0; i < msgList.length; i++) {
        if (msgList[i].msg.channelID == msg.channelID &&
            msgList[i].msg.channelType == msg.channelType) {
          msgList[i].msg = msg;
          //初始化显示内容
          msgList[i].lastContent = await getShowContent(UIConversation(msg));
          isAdd = false;
          uiConversation = msgList[i];
          setState(() {});
          break;
        }
      }
      if (isAdd) {
        //获取频道 没有就触发 获取频道信息 事件 -- 发送人
        msg.getWkChannel().then((value) {
          if (value == null) {
            // 从远程服务器获取channel信息
            WKIM.shared.channelManager
                .fetchChannelInfo(msg.channelID, msg.channelType);
          }
        });
        // msg.getWkChannel().then((value) => uiConversation.wkChannel = value);
        uiConversation = UIConversation(msg);
        //初始化显示内容
        uiConversation.lastContent = await getShowContent(uiConversation);
        msgList.add(uiConversation);
      }
      if (isEnd) {
        setState(() {});
        //播放提示音乐
        AudioTool.play("assets/audio/msg_tip.m4a", filter: msg.channelID);
        bus.emit("bottom_unread");
        //提示音乐与通知冲突
        // var body = uiConversation!.lastContent;
        // body = body.substring(0, body.length > 10 ? 10 : body.length);
        // var channel = await msg.getWkChannel();
        // notificationHelper.showNotification(
        //     id: uiConversation.msg.lastMsgSeq,
        //     title: channel == null ? "消息提醒" : channel.channelName,
        //     body: '$body...');
      }
    });
    //  监听channel刷新事件
    WKIM.shared.channelManager.addOnRefreshListener('chat_conversation',
        (wkChannel) {
      // 刷新对应channel 信息
      debugPrint("监听channel刷新事件  ================ ${wkChannel.channelID} ");
      var ui = msgList.firstWhere((element) {
        return element.msg.channelID == wkChannel.channelID &&
            element.msg.channelType == wkChannel.channelType;
      }, orElse: () {
        return UIConversation(WKUIConversationMsg());
      });
      ui.wkChannel = wkChannel;
      setState(() {});
    });

//  监听获取channel信息
    WKIM.shared.channelManager
        .addOnGetChannelListener((channelId, channelType, back) async {
      debugPrint("监听获取channel信息  ================ $channelId");
      WKChannel wkChannel = WKChannel(channelId, channelType);
      ResEntity resEntity = await ImDao.getChannelInfo(
          {"channel_id": channelId, "channel_type": channelType});
      var data = resEntity.data;
      wkChannel.avatar = data["avatar"];
      wkChannel.channelName = data["channelName"] ?? "";
      wkChannel.channelRemark = data["channelRemark"] ?? "";
      //更新本地channel资料
      // back(wkChannel);
      // 获取到资料后 通过back返回
      WKIM.shared.channelManager.addOrUpdateChannel(wkChannel);
      setState(() {});
    });
    //  监听获取cmd信息
    WKIM.shared.cmdManager.addOnCmdListener("chat_conversation", (cmd) {
      debugPrint("监听获取cmd信息  ================ ${cmd.cmd}");
      if (UserInfo.callable) {
        //语音邀请
        if (cmd.cmd == SysConst.wk_cmd_voice_invite) {
          var channelId = cmd.param["channel_id"];
          if (channelId != UserInfo.uid) {
            // Navigator.push(
            //     context,
            //     MaterialPageRoute(
            //         builder: (context) => CallPage(
            //           channelId: cmd.param["channel_id"],
            //           channelType: cmd.param["channel_type"].toInt(),
            //           roomId: cmd.param["room_id"],
            //           callStatus: CallStatusEnum.waiting,
            //         )));
          }
        }
      } else {
        //退出
        Map<String, dynamic> pm = {};
        pm["cmd"] = SysConst.wk_cmd_voice_refuse;
        pm["param"] = {
          "room_id": cmd.param["room_id"],
          "channel_id": cmd.param["channel_id"],
          "channel_type": WKChannelType.personal
        };
        ImDao.sendCmd(cmd.param["room_id"], WKChannelType.personal, pm);
      }
    });
  }

  void _getDataList() {
    Future<List<WKUIConversationMsg>> list =
        WKIM.shared.conversationManager.getAll();
    list.then((result) async {
      for (var i = 0; i < result.length; i++) {
        var uiConversation = UIConversation(result[i]);
        uiConversation.wkChannel = await result[i].getWkChannel();
        //初始化显示内容
        uiConversation.lastContent = await getShowContent(uiConversation);
        msgList.add(uiConversation);
      }
      setState(() {});
    });
  }

  //初始化显示内容
  Future<String> getShowContent(UIConversation uiConversation) async {
    var value = await uiConversation.msg.getWkMsg();
    if (value != null && value.messageContent != null) {
      uiConversation.lastContent = value.messageContent!.displayText();
      return uiConversation.lastContent;
      // setState(() {});
    }
    uiConversation.lastContent = '';
    return uiConversation.lastContent;
  }

  Widget _buildRow(UIConversation uiMsg) {
    return InkWell(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            // builder: (context) => const ChatPage(),
            builder: (context) => MessagesScreen(
              currentChannel: uiMsg.wkChannel!,
            ),
          ),
        );
      },
      child: Padding(
        padding: const EdgeInsets.symmetric(
            horizontal: kDefaultPadding, vertical: kDefaultPadding * 0.75),
        child: Row(
          children: [
            Stack(
              children: [
                uiMsg.wkChannel == null
                    ? Text(
                        CommonUtils.getAvatar(uiMsg.msg.channelID),
                        style: const TextStyle(
                            color: Colors.white,
                            fontSize: 20,
                            fontWeight: FontWeight.bold),
                      )
                    : CircleAvatar(
                        radius: 24,
                        backgroundImage: NetworkImage(uiMsg.wkChannel!.avatar),
                      ),
                // if (chat.isActive)
                Positioned(
                  bottom: 0,
                  right: 0,
                  child: Container(
                    height: 16,
                    width: 16,
                    decoration: BoxDecoration(
                      color: kPrimaryColor,
                      shape: BoxShape.circle,
                      border: Border.all(
                          color: Theme.of(context).scaffoldBackgroundColor,
                          width: 3),
                    ),
                  ),
                ),
              ],
            ),
            Expanded(
                child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: kDefaultPadding),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    uiMsg.wkChannel == null ? "" : uiMsg.wkChannel!.channelName,
                    style: const TextStyle(
                        fontSize: 16, fontWeight: FontWeight.w500),
                  ),
                  const SizedBox(height: 8),
                  Opacity(
                      opacity: 0.64,
                      child: Text(
                        uiMsg.lastContent,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      )),
                ],
              ),
            )),
            Padding(
              padding:
                  const EdgeInsets.symmetric(horizontal: kDefaultPadding / 5),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Opacity(
                    opacity: 0.64,
                    child: Text(
                        TimeUtils.getComparedTime(uiMsg.msg.lastMsgTimestamp)),
                  ),
                  const SizedBox(height: 8),
                  if (uiMsg.getUnreadCount() != '')
                    Stack(
                        textDirection: TextDirection.rtl,
                        fit: StackFit.loose,
                        alignment: Alignment.centerRight,
                        clipBehavior: Clip.none,
                        children: <Widget>[
                          Container(
                            padding: const EdgeInsets.all(3),
                            decoration: BoxDecoration(
                              color: Colors.red,
                              borderRadius: BorderRadius.circular(6),
                            ),
                            constraints: const BoxConstraints(
                              minWidth: 12,
                              minHeight: 12,
                            ),
                            child: Text(
                              uiMsg.getUnreadCount(),
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 8,
                              ),
                              textAlign: TextAlign.center,
                            ),
                          ),
                        ]),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_connectionStatusStr),
      ),
      body: ListView.builder(
          shrinkWrap: true,
          itemCount: msgList.length,
          itemBuilder: (context, pos) {
            return GestureDetector(
              onTap: () {
                debugPrint("点击------------------");
                // var indexChannelId = msgList[pos].msg.channelID;
                // var indexChannelType = msgList[pos].msg.channelType;
                // Navigator.push(
                //   context,
                //   MaterialPageRoute(
                //     builder: (context) => const ChatPage(),
                //     settings: RouteSettings(
                //       arguments: ChatChannel(
                //         indexChannelId,
                //         indexChannelType,
                //       ),
                //     ),
                //   ),
                // );
              },
              child: _buildRow(msgList[pos]),
            );
          }),
    );
  }
}
